using System;
using System.Collections;
using System.Collections.Generic;
using UMC.Data;
using UMC.Web;
using UMC.WorkFlow.Entities;
using UMC.WorkFlow.Form;
using UMC.WorkFlow.Subassembly;

namespace UMC.WorkFlow
{


    [Apiumc("WorkFlow", "Command", Auth = WebAuthType.Guest, Desc = "表单审批")]
    public class WorkFlowCommandActivity : WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            TaskForm taskForm = null;
            var Task = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Task", k =>
            {
                var Code = this.AsyncDialog("Code", "none");
                if (Code == "none")
                {
                    this.Prompt("缺少参数");
                }
                taskForm = DataFactory.Instance().TaskForm(Code);

                if (taskForm == null)
                {
                    this.Prompt("未有此流程");
                }
                return this.DialogValue(taskForm.TaskId.ToString());

            })).Value;
            if (taskForm == null)
            {
                taskForm = DataFactory.Instance().TaskForm(Task); ;

                if (taskForm == null)
                {
                    this.Prompt("未有此流程");
                }
            }
            var InstanceId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("InstanceId", "none")) ?? 0;


            var cmds = InstanceId == 0 ? FormManager.GetCommands(taskForm.TaskId.Value, new Identity(this.Context.Token))
                : FormManager.GetCommands(taskForm.TaskId.Value, InstanceId, new Identity(this.Context.Token));
            var type = this.AsyncDialog("Type", "auto");
            if (type == "command")
            {

                var data = new System.Data.DataTable();
                data.Columns.Add("Id");
                data.Columns.Add("Text");
                data.Columns.Add("Shape");

                Utility.Each(cmds, g => data.Rows.Add(g.Id, g.Text, g.ShapeId));
                response.Redirect(data);
            }

            var task = TaskManager.Instance(InstanceId);
            if (cmds.Length == 0)
            {
                if (task != null)
                {
                    if (task.Status == TaskStatus.Completed)
                    {
                        this.Prompt("流程已经完成");
                    }
                    else
                    {
                        this.Prompt("您没有审批权限");
                    }
                }
                else
                {
                    this.Prompt("您无提交的权限");
                }
            }
            var cmd = this.AsyncDialog("Command", g =>
            {
                if (cmds.Length == 1)
                {
                    return this.DialogValue(cmds[0].Id);
                }
                var fm = new UMC.Web.UISelectDialog() { Title = "流程审批" };
                foreach (var c in cmds)
                {
                    fm.Options.Add(new ListItem() { Text = c.Text, Value = c.Id });
                }
                return fm;
            });


            var Explain = UMC.Web.UIDialog.AsyncDialog(this.Context, "Explain", g =>
            {

                var checkData = new List<TaskCheckContorl>();
                var DefaultEdit = false;
                foreach (var m in cmds)
                {
                    switch (m.Command)
                    {
                        case CommandType.Save:
                        case CommandType.Submit:
                            DefaultEdit = true;
                            break;
                    }
                }
                var ShapeId = "Default";
                if (cmds.Length > 0)
                {
                    ShapeId = cmds[0].ShapeId;
                    var controls = HotCache.Find(new TaskFormControl
                    {
                        TaskId = taskForm.TaskId,
                        ForId = 0
                    });
                    if (controls.Length > 0)
                    {
                        var ids = new List<ulong?>();
                        foreach (var f in controls)
                        {
                            ids.Add(f.ItemId.Value);
                        }
                        var searcher = HotCache.Search<TaskCheckContorl>();
                        checkData.AddRange(searcher.In(new TaskCheckContorl { ShapeId = "Default" }, ShapeId)
                          .And().In(new TaskCheckContorl { ItemId = ids[0] }, ids).Query(new TaskCheckContorl(), false, 0, 10000, out var _));
                    }


                    var taskData = new List<TaskData>(DataFactory.Instance().TaskData(InstanceId));


                    if (taskData.Exists(k => String.Equals(k.DataName, "ApplyNO", StringComparison.CurrentCultureIgnoreCase)) == false)
                    {

                        var ApplyNO = SubassemblyHelper.ApplyNO(taskForm);
                        var tdata = new TaskData
                        {
                            DataName = "ApplyNO",
                            DataIndex = -1,
                            DataText = ApplyNO,
                            DataValue = ApplyNO,
                            InstanceId = InstanceId
                        };
                        DataFactory.Instance().Put(tdata);

                        taskData.Add(tdata);
                    }
                    var pdata = new Hashtable();
                    UMC.Data.Utility.Each(taskData.FindAll(td => td.DataIndex == -1), dr =>
                         {
                             pdata[dr.DataName] = dr.DataValue;
                         });
                    pdata["InstanceId"] = InstanceId;
                    pdata["TaskId"] = taskForm.TaskId;

                    foreach (var ctl in controls)
                    {
                        if (ctl.Type == ControlType.Readonly)
                        {
                            continue;
                        }
                        var isEdit = DefaultEdit;
                        var checks = checkData.FindAll(c => c.ItemId == ctl.ItemId);
                        switch (checks.Count)
                        {
                            case 0:

                                break;
                            case 1:
                                switch (checks[0].ContorlMode)
                                {
                                    case UIContorlMode.Edit:
                                        isEdit = true;
                                        break;
                                    case UIContorlMode.Hidden:
                                        continue;
                                    case UIContorlMode.Readonly:
                                        isEdit = false;
                                        break;
                                    case UIContorlMode.Normal:
                                        break;
                                }
                                break;
                            case 2:
                                switch ((checks.Find(c => c.ShapeId == ShapeId) ?? checks[0]).ContorlMode)
                                {
                                    case UIContorlMode.Edit:
                                        isEdit = true;
                                        break;
                                    case UIContorlMode.Hidden:
                                        continue;
                                    case UIContorlMode.Readonly:
                                        isEdit = false;
                                        break;
                                    case UIContorlMode.Normal:
                                        break;
                                }
                                break;
                        }
                        if (ctl.IsRequired == true)
                        {
                            if (isEdit)
                            {

                                var ta = taskData.Find(e => e.DataName == ctl.Code);
                                if (ta == null || String.IsNullOrEmpty(ta.DataValue))
                                {
                                    if (String.IsNullOrEmpty(ctl.RequiredSQL) == false)
                                    {
                                        var dic = String.Format("{0}", Database.Instance(taskForm.ProviderKey)
                                            .Sqler(false).ExecuteScalar(ctl.RequiredSQL, pdata));

                                        if (Utility.IntParse(dic, 0) <= 0)
                                        {
                                            continue;
                                        }

                                    }
                                    if (String.IsNullOrEmpty(ctl.PlaceHolder) == false)
                                    {
                                        this.Prompt(ctl.PlaceHolder);
                                    }
                                    else
                                    {
                                        this.Prompt(String.Format("{0}没有值", ctl.Caption));
                                    }
                                }
                            }
                        }
                    }
                    pdata["Task.Text"] = taskForm.Caption;

                    var subject = String.Format("{0}发起 {1} ", this.Context.Token.Alias, taskForm.Caption);
                    if (String.IsNullOrEmpty(taskForm.SubjectFormat) == false)
                    {
                        subject = Utility.Format(taskForm.SubjectFormat, pdata);
                    }
                    var subdata = taskData.Find(k => String.Equals(k.DataName, "subject", StringComparison.CurrentCultureIgnoreCase));
                    if (subdata == null)
                    {
                        var tdata = new TaskData
                        {
                            DataName = "Subject",
                            DataIndex = -1,
                            DataText = subject,
                            DataValue = subject,
                            InstanceId = InstanceId
                        };
                        DataFactory.Instance().Put(tdata);

                        taskData.Add(tdata);
                    }
                    else if (String.Equals(subject, subdata.DataValue) == false)
                    {

                        DataFactory.Instance().Put(new TaskData
                        {
                            DataName = "Subject",
                            DataIndex = -1,
                            InstanceId = InstanceId,
                            DataText = subject,
                            DataValue = subject,
                        });

                    }
                }
                var d = new List<TaskButton>();
                d.AddRange(cmds);
                var btn = d.Find(k => k.Id == cmd);
                var fm = new UMC.Web.UIFormDialog() { Title = "审批意见" };


                fm.AddTextValue().Put("执行审批", btn.Command == CommandType.Submit ? "申请" : btn.Text);
                 
                switch (btn.Command)
                {
                    case CommandType.Apostille:
                        fm.AddOption("加签人员", "Apostille").Command("Settings", "SelectUser").PlaceHolder("请选择加签人员");
                        break;
                    case CommandType.Save:
                        return this.DialogValue(btn.Text);
                }

                fm.AddTextarea("审批意见", "Explain", btn.Text).Put("tip", "审批意见");//.NotRequired();

                fm.Submit("确认指令", "WorkFlow.Progress");
                return fm;
            });

            var UIData = new Hashtable((request.SendValues ?? request.Arguments).GetDictionary());//? .GetDictionary());
            UIData.Remove("Command");
            UIData.Remove("Explain");
            UIData.Remove("InstanceId");
            UIData.Remove("KEY_DIALOG_ID");
            UIData.Remove("Task");

            UIData.Remove("Type");
            UIData.Remove("Code");
            if (UIData.Count > 0)
            {
                var keys = new List<String>();
                var uidata = new List<TaskData>();
                var emUI = UIData.GetEnumerator();
                while (emUI.MoveNext())
                {
                    var key = emUI.Key as string;
                    if (key.StartsWith("Apostille") == false)
                    {
                        uidata.Add(new TaskData
                        {
                            DataIndex = -1,
                            DataName = key,
                            DataValue = emUI.Value as string,
                            DataText = emUI.Value as string,
                            InstanceId = InstanceId
                        });
                        keys.Add(key);
                    }
                }
                if (keys.Count > 0)
                {
                    keys.RemoveAll(ui => uidata.Exists(c => c.DataName == ui));
                    foreach (var k in keys)
                    {
                        var vs = DataFactory.Instance().TaskData(InstanceId, k);
                        foreach (var v in vs)
                        {
                            DataFactory.Instance().Delete(v);
                        }

                    }
                    foreach (var u in uidata)
                    {

                        DataFactory.Instance().Put(u);
                    }
                }
            }
            UIData["Explain"] = Explain;
            var cmdType = CommandType.Undefine;
            var cmdIndex = cmd.IndexOf('.');
            if (cmdIndex > -1)
            {
                cmdType = UMC.Data.Utility.Parse(cmd.Substring(0, cmdIndex), cmdType);
                var Key = cmd.Substring(cmdIndex + 1);
                if (String.IsNullOrEmpty(Key) == false)
                {
                    if (cmdType == CommandType.Reject)
                    {
                        UIData["Reject.To"] = Key;
                    }
                    else
                    {
                        UIData["CommandKey"] = Key;

                    }
                }
            }
            else
            {
                cmdType = UMC.Data.Utility.Parse(cmd, cmdType);
            }
            var resit = FormManager.Progress(this.Context.Token, Task, cmdType, UIData, InstanceId);


            if (type == "API")
            {
                response.Redirect(resit);

            }
            else if (resit.Success == false)
            {
                this.Prompt("错误", resit.Message, false);
            }
            this.Context.Send("WorkFlow.Progress", new WebMeta().Put("Result", resit), true);
            //}


        }
    }
}